<template>
<div class="dashboard">
  <div class="header">
    <div class="quit-info">
      <div class="quit" @click="handleExit">退出</div>
    </div>
    <div class="title">
      <img src="./img/titleCockpit.png" alt="">
      <div class="head-selection">
      <el-select  style="width:120px" class="mr10" size="mini" v-model="queryParams.divisionId"
      placeholder="组件事业部" >
        <el-option
          v-for="item in deptList"
          :key="item.divisionId"
          :label="item.divisionName"
          :value="item.divisionId">
        </el-option>
      </el-select>
      <el-select style="width:120px" size="mini" v-model="queryParams.baseId" filterable clearable placeholder="全部基地" >
        <el-option
          v-for="item in factoryList"
          :key="item.baseId"
          :label="item.baseName"
          :value="item.baseId">
        </el-option>
      </el-select>
      </div>
    </div>
    <div class="info">

      <div class="info-date">{{today.toLocaleString().replace(/\//g,'-')}} 星期{{days[today.getUTCDay()]}}</div>


    </div>
  </div>
  <div class="body" ref="body">
    <el-row type="flex"  style="flex:1">
      <!-- 左侧 -->
      <el-col :span="7" :style="{width:((bodyWidth-16)/24) * 7+'px'}">
        <div class="echart-box" style="margin-bottom: 8px;" :style="{width:((bodyWidth-16)/24) * 7+'px',height:(bodyHeight-8)/2 + 'px'}">
          <div class="echart-head">
            <el-date-picker
              class="echarts-head-date"
              size="mini"
              style="width:220px"
              v-model="echart1Range"
              :type="echart1Type"
              format="yyyy年MM月dd日"
              value-format="yyyy-MM-dd"
              :range-separator="$t('cockpit.to')"
              @change="handleEchart1DateChange"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
              <el-button type="primary" :plain="echart1Tag != 'daterange'" class="echarts-head-button" size="mini" @click=" echart1Type= 'daterange';echart1Range=[];echart1Tag='daterange';queryParams1.dateType='0';">{{$t('cockpit.dayPasses')}}</el-button>

              <el-button  type="primary" :plain="echart1Tag != 'week'" class="echarts-head-button" size="mini" @click=" echart1Range=null;echart1Type= 'daterange';echart1Tag='week';queryParams1.dateType='1';">{{$t('cockpit.weeksGoBy')}}</el-button>

              <el-button  type="primary" :plain="echart1Tag != 'monthrange'"  class="echarts-head-button" size="mini" @click=" echart1Type= 'monthrange';echart1Range=[];echart1Tag='monthrange';queryParams1.dateType='2';">{{$t('cockpit.monthPasses')}}</el-button>

          </div>
          <!-- 左1 -->
          <div ref="echart1"  :style="{width:((bodyWidth-16)/24) * 7+'px',height:(bodyHeight-8)/2 + 'px'}"></div>
        </div>
        <div class="echart-box" :style="{width:((bodyWidth-16)/24) * 7+'px',height:(bodyHeight-8)/2 + 'px'}">

          <div class="echart-head">

            <el-date-picker
              class="echarts-head-date"
              size="mini"
              v-model="queryParams2.time"
              type="month"
              value-format="yyyy-MM"
              format="yyyy年MM月"
              :placeholder="$t('cockpit.selectMonth')">
            </el-date-picker>
              <el-button  type="primary" plain class="echarts-head-button" size="mini" @click="handleQueryEchart2">{{$t('public.query')}}</el-button>

              <el-button  type="primary" plain  class="echarts-head-button" size="mini" @click="handleQueryEchart2(0)">{{$t('public.reset')}}</el-button>

          </div>
          <!-- 左2 -->
          <div ref="echart2" style="width:100%;" :style="{width:((bodyWidth-16)/24) * 7+'px',height:(bodyHeight-8)/2 + 'px'}"></div>
        </div>


      </el-col>
       <!-- 中间 -->
      <el-col :span="10" style="margin: 0 8px;" :style="{width:((bodyWidth-16)/24) * 10+'px'}" >
        <div class="dv-section">
          <div class="dv-title">{{ $t('cockpit.incomingMaterialInspectionTasks') }}</div>
          <dv-scroll-board :config="config1"  :style="{width:'100%', height: `${(bodyHeight-75)*0.66}px` }" />
        </div>
        <div class="dv-section mt5">
          <div class="dv-title">{{ $t('cockpit.mbrProcessingStatus') }}</div>
          <dv-scroll-board :config="config2"  :style="{width:'100%', height: `${(bodyHeight-75)*0.34}px` }" />
        </div>

      </el-col>
      <!-- 右侧 -->
      <el-col :span="7"  :style="{width:((bodyWidth-16)/24) * 7+'px'}">
        <div class="echart-box" style="margin-bottom: 8px" :style="{height:(bodyHeight-16)/3 + 'px'}">
          <div class="echart-head">
            <el-date-picker
              class="echarts-head-date"
              size="mini"
              v-model="echart3Range"
              type="daterange"
              :range-separator="$t('cockpit.to')"
              value-format="yyyy-MM-dd"
              format="yyyy年MM月dd日"
              @change="handleEchart3DateChange"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <el-button  type="primary" plain class="echarts-head-button" size="mini" @click="handleQueryEchart3">{{$t('public.query')}}</el-button>

            <el-button  type="primary" plain  class="echarts-head-button" size="mini" @click="handleQueryEchart3(0)">{{$t('public.reset')}}</el-button>
          </div>
          <div ref="echart3" style="width:100%;" :style="{height:(bodyHeight-16)/3 + 'px'}"></div>
        </div>
        <div class="echart-box" style="margin-bottom: 8px" :style="{height:(bodyHeight-16)/3 + 'px'}">
          <div class="echart-head">
            <el-date-picker
              class="echarts-head-date"
              size="mini"
              v-model="echart4Range"
              type="daterange"
              :range-separator="$t('cockpit.to')"
              format="yyyy年MM月dd日"
              value-format="yyyy-MM-dd"
              @change="handleEchart4DateChange"
              start-placeholder="开始日期"
              end-placeholder="结束日期">
            </el-date-picker>
            <el-button  type="primary" plain class="echarts-head-button" size="mini" @click="handleQueryEchart4">{{$t('public.query')}}</el-button>

            <el-button  type="primary" plain  class="echarts-head-button" size="mini" @click="handleQueryEchart4(0)">{{$t('public.reset')}}</el-button>
          </div>
          <div ref="echart4" style="width:100%;" :style="{height:(bodyHeight-16)/3 + 'px'}"></div>
        </div>
        <div class="echart-box" :style="{height:(bodyHeight-16)/3 + 'px'}">
          <div class="echart-head">
            <!-- <el-select  style="width:120px" class="mr10" size="mini" v-model="queryParams5.materialCode"
              placeholder="选择物料" @change="handleChange($event,'auditType')">
              <el-option
                v-for="item in materialList"
                :key="item"
                :label="item"
                :value="item">
              </el-option>
            </el-select> -->
            <el-cascader :placeholder="$t('cockpit.selectMaterialCategory')" class="echarts-head-date"
                      ref="cascader"
                      :value="queryParams5.categoryIds"
                      :options="materialList"
                      :show-all-levels=false
                      :collapseTags=true
                      :props="{ multiple:true, expandTrigger:'hover',emitPath:false,checkStrictly: true,value:'id',label:'label' }"
                      clearable  @change="cascaderChange"
                       size="mini"
                  ></el-cascader>
            <el-date-picker
              class="echarts-head-date"
              size="mini"
              style="width:110px"
              v-model="queryParams5.time"
              type="month"
              value-format="yyyy-MM"
              format="yyyy年MM月"
              :placeholder="$t('cockpit.selectMonth')">
            </el-date-picker>
            <el-button  type="primary" plain class="echarts-head-button" size="mini" @click="handleQueryEchart5">{{$t('public.query')}}</el-button>

            <el-button  type="primary" plain  class="echarts-head-button" size="mini" @click="handleQueryEchart5(0)">{{$t('public.reset')}}</el-button>

          </div>
          <div ref="echart5" v-if="visibleEchart56" style="width:100%;" :style="{height:(bodyHeight-16)/3 + 'px'}"></div>
          <div ref="echart6" v-if="!visibleEchart56" style="width:100%;position: absolute;top:0;left:0;z-index: 1" :style="{height:(bodyHeight-16)/3 + 'px'}"></div>
        </div>
      </el-col>
    </el-row>
  </div>
  <dialog-detail :visible.sync="visible" :data="dataMet"></dialog-detail>
  <dialog-detail-stu :visible.sync="visibleStu" :data="dataStu"></dialog-detail-stu>
  <dialog-detail-mrb :visible.sync="visibleMrb" :data="dataMrb"></dialog-detail-mrb>
  <dialog-detail-met :visible.sync="visibleMea" :data="dataMea"></dialog-detail-met>
  <dialog-detail-sup :visible.sync="visibleSup" :data="dataSup"></dialog-detail-sup>
</div>


</template>

<script>
import { getInventoryList,getNcrReviewList, materialChart,qualifiedChart, materialList, checkStatusChart, nonconFormingStatusChart, supplierChart,supplierOneChart,categorylistAPI} from '@/api/inspectionManagement/inspectionManagement'
import { divisionList } from '@/api/masterdata/division'
import { listBaseFactory,listALLFactory,listBaseAPI } from '@/api/basic/factory'
import DialogDetail from "./dialogDetail"
import DialogDetailMet from "./dialogDetailMet"
import DialogDetailStu from "./dialogDetailStu"
import DialogDetailMrb from "./dialogDetailMrb"
import DialogDetailSup from "./dialogDetailSup"
import mixins from './mixins'
import moment from 'moment';

const startTime = moment().startOf('month').format('YYYY-MM-DD')
const endTime = moment().endOf('month').format('YYYY-MM-DD')
export default {
  name: "dashboard",
  dicts: ['AUDIT_TYPE','NYIQC_NCR_DECISION'],
  components: {DialogDetail,DialogDetailMrb,DialogDetailStu,DialogDetailSup,DialogDetailMet},
  mixins: [mixins],
  data(){
    let visitSource = this.$t('cockpit.visitSource');
    let inProgress = this.$t('cockpit.inProgress');
    let closed = this.$t('cockpit.closed');
    return {
      today:new Date(),
      ncrStateMap:{visitSource:  3, inProgress:  0 , closed:  2},
      days: ['日','一','二','三','四','五','六'],
      echart1Range: [startTime,endTime],
      echart2Range: [startTime,endTime],
      echart3Range: [startTime,endTime],
      echart4Range: [startTime,endTime],
      echart1Tag: 'daterange',
      echart1Type: 'daterange',
      curEchart1Type: null,
      echart2Date:null,
      echart2Type: 'daterange',
      deptList: null,
      factoryList: null,
      dataMet: null,
      visibleEchart56: true,
      visible: false,
      visibleMrb: false,
      dataMrb: null,
      visibleStu: false,
      dataStu: null,
      visibleSup: false,
      dataSup: null,
      visibleMea: false,
      dataMea: null,
      bodyWidth:0,
      bodyHeight:0,
      isFullscreen: false,
      multiple: false,
      clearable: false,
      queryParams:{divisionId:null,baseId:null},
      queryParams1: {
        startTime,
        endTime,
        dateType: '0'
      },
      queryParams2:{
        time:null,
        dateType: "2",
      },
      queryParams3:{
        startTime,
        endTime,
        dateType: "0",
      },
      queryParams4:{
        startTime,
        endTime,
        dateType: "0",
      },
      queryParams5:{
        categoryIds:[],
        time:null,
      },
      queryParams6:{},
      materialList:[],
      config1:{
        header: [this.$t('cockpit.sendankujiIssue'), this.$t('cockpit.dateOfSubmission'),this.$t('mrbForm.materialName'), this.$t('cockpit.supplierMaterialBatch'), this.$t('mrbForm.supplierName'),this.$t('basicData.materialType'),this.$t('cockpit.deliveryOrderNumber'),this.$t('inventoryManagement.location'),this.$t('inventoryManagement.purchaser')],
        rowNum: 10,
        // index: true,
        align: ['center','left','left','left','left','left','left','left','left'],
        columnWidth:[80,90,140,140,140,80,140,160,100,],
        // headerBGC: '#0873DC',
        headerBGC: 'transparent',
        oddRowBGC:'#001B77',
        evenRowBGC:'#001766',
        data: undefined
      },
      config2:{
        header: [this.$t('mrbForm.mrbOrder'), this.$t('public.title'), this.$t('inventoryManagement.purchaser'), this.$t('inspectionManagement.materialBatch'), this.$t('inspectionManagement.materialName'),this.$t('supplier.supplierName'), this.$t('cockpit.mrbDecision'), this.$t('mrbForm.mrbStatus')],
        rowNum: 5,
        index: true,
        align: ['center','left','left','left','left','left','left','left','left'],
        columnWidth:[80,90,140,140,140,80,140,160,100,100],
        // headerBGC: '#0873DC',
        headerBGC: 'transparent',
        oddRowBGC:'#001B77',
        evenRowBGC:'#001766',
        data: undefined
      },
    }
  },
  watch:{
    ["queryParams.divisionId"](val){
      if(val){
          this.listALLFactory(1)
      }
    },
    ["queryParams.baseId"](val){
      if(val && this.queryParams.divisionId){
        this.listALLFactory(2)
      }
    }
  },
  mounted(){
    this.domInit()
    this.initPage()
  },
  methods:{
    async changedivisionId( ){

      await listBaseAPI( this.queryParams.divisionId ).then(res=> {
        this.factoryList = res.data
        const {baseId, baseName} = res?.data[0] || {}
        this.queryParams.baseId = baseId
      })
    },
    cdsss(children){
      for (const iterator of children) {
        if(this.queryParams5.categoryIds.indexOf(iterator.value) == -1){
          this.queryParams5.categoryIds.push(iterator.value)
        }
        this.cdsss(iterator.children)
      }
      // 结束时保存选中节点
      this.queryParams5.categoryIds = [...this.queryParams5.categoryIds]
      this.$forceUpdate()
    },
    cdxDeep(id,children){
      for (const iterator of children) {
        let index = this.queryParams5.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams5.categoryIds.splice(index,1) : ''
          this.cdxDeep(id,iterator.children ? iterator.children : [])
      }
    },
    cdxxx(id,children){
      for (const iterator of children) {
        if(id == 'deep'){
          let index = this.queryParams5.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams5.categoryIds.splice(index,1) : ''
          this.cdxDeep('deep',iterator.children ? iterator.children : [])
        }
        if(iterator.id == id){
          let index = this.queryParams5.categoryIds.indexOf(iterator.id)
          index != -1 ? this.queryParams5.categoryIds.splice(index,1) : ''
          this.cdxDeep('deep',iterator.children ? iterator.children : [])
          return
        }else{
          this.cdxxx(id,iterator.children ? iterator.children : [])
        }
      }
    },
    cascaderChanges(children){
      console.log(children,this.queryParams5.categoryIds)
      let queryParamsCategoryIds = [...this.queryParams5.categoryIds]
      if(children.length <= this.queryParams5.categoryIds.length){
        let deleteCaId = null
        for (const id of this.queryParams5.categoryIds) {
          if(children.indexOf(id) == -1){
            deleteCaId = id
            break;
          }
        }
        console.log('删除操作')
        this.cdxxx(deleteCaId,this.materialList)
      }else{
        console.log('新增操作')
        // this.queryParams.categoryIds = []
        console.log(this.$refs['cascader'].getCheckedNodes())
        let children = this.$refs['cascader'].getCheckedNodes()
        console.log(children)
        console.log(this.queryParams5.categoryIds)
        children = children.filter(val => queryParamsCategoryIds.indexOf(val.value) == -1)
        console.log(children,'传送的NODE项')
        this.cdsss(children)
      }
    },
    cascaderChange(children) {
      // let checkedNodes = this.$refs['cascader'].getCheckedNodes();
      // this.queryParams5.categoryId = checkedNodes[0].data.id
     console.log(this.queryParams5)
     this.cascaderChanges(children)
    },
    async listALLFactory(n){
      if(n==1){
        await this.changedivisionId()
      }
      const { divisionId,baseId } = this.queryParams
      await listALLFactory({divisionId,baseId:baseId?baseId:undefined}).then(res=>{
        if(res.data ){
          const plantCodes = res.data.map(i=>i.plantCode)
          this.queryParams.plantCode = plantCodes
          this.initChart(plantCodes)
        }else{
          this.echart1?.dispose()
          this.echart2?.dispose()
          this.echart3?.dispose()
          this.echart4?.dispose()
          this.echart5?.dispose()
          this.echart6?.dispose()
        }
      })
    },
    domInit() {
      const self = this;
      /** 监听文本框内容高度*/
      const observer = new ResizeObserver((entries) => {
        entries.forEach((entry) => {
          const cr = entry.contentRect;
          self.bodyWidth = cr.width
          self.bodyHeight = cr.height
        });
      });
      observer.observe(this.$refs.body);
    },
    handleEchart1DateChange(e){
      console.log(e)
      this.queryParams1 = {
          ...this.queryParams1,
          startTime: e[0],
          endTime: e[1],
      }
      this.handleQueryEchart1(this.queryParams.plantCode)
    },
    handleEchart3DateChange(e){
      console.log(e)
      this.queryParams3 = {
          ...this.queryParams3,
          startTime: e?e[0]:undefined,
          endTime: e?e[1]:undefined,
      }
    },
    handleEchart4DateChange(e){
      console.log(e)
      this.queryParams4 = {
          ...this.queryParams4,
          startTime: e?e[0]:undefined,
          endTime: e?e[1]:undefined,
      }
    },
    handleExit(){
      window.opener = null;
      window.open('','_self');
      window.close();
      this.$router.go(-1)
    },
    async initPage(){
      //事业部门
      await divisionList().then(res=>{
        this.deptList = res.rows
        this.queryParams.divisionId = res.rows[0]?.divisionId
      })
      //厂区
      await listBaseAPI( this.queryParams.divisionId ).then(res=> {
        this.factoryList = res.data
        const {baseId, baseName} = res.data[0] || {}
        this.queryParams.baseId = baseId
      })
      //中间表1
      getInventoryList({pageNum: 1, pageSize: 100, coverStatus: 0}).then(res => {
        this.config1 = {...this.config1, data: res.rows.map(i=>{
            return [i.inspectionLotMark, i.deliveryDate, i.materialName, i.lichn, i.supplierName, i.materialType, i.lsVbeln,i.lgort, i.createBy ]
          })}
      })
      //中间表2
      getNcrReviewList({pageNum:1,pageSize:100}).then(res=>{
        // header: ['MRB流程编号', '标题', '申请人', '物料批次', '物料名称',"供应商名称"],
        this.config2 = {...this.config2, data: res.rows.map(i=>{
            return [i.ncrProcessId, i.title, i.createBy, i.lot, i.materialName, i.supplierName, this.formatCE_NCR(i.usingDecision), this.getStatusStr(i.ncrStatus) ]
          })}
      })

    },

    formatCE_NCR(e) {
        if (e) {
            let obj = this.dict.type.NYIQC_NCR_DECISION.find((item) => {
                return item.value === e
            })
            if (obj) {
                return obj.label
            } else {
                return ''
            }
        } else {
            return ''
        }
    },
    getStatusStr(stu){
      let status_str = null
      for(let key in this.ncrStateMap){
        if(stu == this.ncrStateMap[key]){
          status_str = key
        }
      }
      return status_str
    },

    handleQueryEchart1(){
     const { startTime, endTime,dateType} = this.queryParams1
     const { plantCode} = this.queryParams
     qualifiedChart({
       "dateType": dateType, //时间类型 0-日 1-周 2-月 3-季 4-年
       "factoryCode": plantCode,
       "startTime": startTime,
       "endTime": endTime}).then(res=>{
       const {date, qualifiedList,ratioList} = res.data||{}
       this.initChart1(date,qualifiedList,ratioList)
     },err=>{
       this.initChart1([],[],[])
     })
   },
    handleQueryEchart2(tag){
      if(tag===0){this.queryParams2.time = null}
      const { time, dateType} = this.queryParams2
      const { plantCode } = this.queryParams
      materialChart({
        "dateType": dateType, //时间类型 0-日 1-周 2-月 3-季 4-年
        "factoryCode": plantCode,
        "time":time}).then(res=>{
        this.initChart2(res.data||{})
      },err=>{
        this.initChart2({materialVos:[]})
      })
    },
    handleQueryEchart3(tag){
      if(tag===0){this.queryParams3.startTime = null;this.queryParams3.endTime = null; this.echart3Range = null}
      const { startTime, endTime,dateType} = this.queryParams3
      const { plantCode} = this.queryParams
      checkStatusChart({
        "dateType": dateType, //时间类型 0-日 1-周 2-月 3-季 4-年
        "startTime": startTime,
        "endTime": endTime,
        "factoryCode": plantCode,
      }).then(res=>{
        this.initChart3(res.data||[])
      },err=>{
        this.initChart3([])
      })
    },
    handleQueryEchart4(tag){
      if(tag===0){this.queryParams4.startTime = null;this.queryParams4.endTime = null;this.echart4Range = null}
      const { startTime, endTime,dateType} = this.queryParams4
      const { plantCode} = this.queryParams
      nonconFormingStatusChart({
        "startTime": startTime,
        "endTime": endTime,
        "factoryCode": plantCode,
      }).then(res=>{
        this.initChart4(res.data||[])
      },err=>{
        this.initChart4([])
      })
    },
    handleQueryEchart5(tag){
      if(tag===0){
        this.echart5?.dispose()
        this.echart6?.dispose()
        this.visibleEchart56 = true;
        this.queryParams5.time = null;
        this.queryParams5.categoryIds = [];
      }
      const { time,categoryIds } = this.queryParams5
      const { plantCode} = this.queryParams
      supplierChart({
        "categoryIds": categoryIds,
        "time":time,
        "factoryCode": plantCode,
      }).then(res=>{
        this.initChart5(res.data||[])
      },err=>{
        this.initChart5([])
      })
    },
    handleQueryEchart6(tag){
      // if(tag===0){this.queryParams5.time = null;this.queryParams5.materialCode = null;}
      const { time,materialCode } = this.queryParams5
      const { plantCode} = this.queryParams
      supplierOneChart({
        supplierCode:null,
        "materialCode": materialCode,
        "time":time,
        "factoryCode": plantCode,
      }).then(res=>{
        this.initChart6(res.data||[])
      })
    },
    handleQueryEchart7(){
      const { plantCode} = this.queryParams
      getInventoryList({
        pageNum:1,pageSize:100,
        factoryCode: plantCode?.join(',')||undefined,
        coverStatus: 0
      }).then(res=>{
        this.config1 = {...this.config1, data: res.rows.map(i=>{
            return [i.inspectionLotMark, i.deliveryDate, i.materialName, i.lichn, i.supplierName, i.materialType, i.lsVbeln,i.lgort, i.createBy ]
          })}
      })
    },
    initChart(plantCodes) {

      // if(!(plantCodes && plantCodes.length))return;
        //选择物料下拉列表数据
        // materialList({
        //   "dateType": '2', //时间类型 0-日 1-周 2-月 3-季 4-年
        //   "factoryCode": plantCodes,
        //   "startTime": "2023-06-01",
        //   "endTime": "2023-06-30"}).then(res=>{
        //   this.materialList = res.data
        // })
        categorylistAPI().then(res=>{
          this.materialList = res.data
        })
        //echart1
        this.handleQueryEchart1()

        //echart2
        this.handleQueryEchart2()

        //echart3
        this.handleQueryEchart3()

        //echart4
        this.handleQueryEchart4()

        //echart5
        this.handleQueryEchart5()

        // echart5
        this.handleQueryEchart7()
    },
  }
}
</script>

<style scoped src="./index.scss" lang="scss"></style>
